import cv2
from time import sleep
import numpy
from datetime import datetime
import serial
import picamera
import shutil
from os import system

def calculate_mean(): #利用YUV格式，输出图像的Y平均值
    with picamera.PiCamera() as camera: # 引入picamera
        stream = open('image.data', 'w+b') #numpy必须使用文件方式读入，所以在这里打开一个文件流
        camera.framerate = 10 # 帧率，参照API文档
        sleep(1) 
        camera.shutter_speed = 36850 #快门速度
        camera.exposure_mode = 'off' #
        g = camera.awb_gains #
        camera.iso = 100 # ISO
        camera.awb_mode = 'off' #
        camera.awb_gains = g #
        width = 1280 #分辨率设置
        height = 720
        camera.resolution = (width, height) #设置分辨率
        camera.capture(stream, 'yuv') # YUV raw data
        stream.seek(0)
        fwidth = (width + 31) // 32 * 32 # Resim Boyutlarini Ayarla
        fheight = (height + 15) // 16 * 16
        # Y kanalini (isiklandirma) cikart
        Y = numpy.fromfile(stream, dtype=numpy.uint8, count=fwidth*fheight).\
        reshape((fheight, fwidth))
        return (numpy.average((numpy.average(Y, axis=0)))) # 计算图像平均Y值